<template>
  <div style="position: fixed; top: 20px; left: 20px">
    <input type="range" min="0" max="1" step="0.01" v-model="value1" />
    <input type="range" min="0" max="1" step="0.01" v-model="value2" />
  </div>
  <div id="container"></div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import * as THREE from "three/webgpu";
import { RGBELoader } from "three/addons/loaders/RGBELoader.js";

import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { MeshoptDecoder } from "three/addons/libs/meshopt_decoder.module.js";
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);

let camera, scene, renderer, wheels;
onMounted(() => {
  init();
  render();
});
const value1 = ref(0);
const value2 = ref(1);

const material = new THREE.MeshStandardMaterial({
  color: new THREE.Color("#f00"),
  roughness: value1.value * 1,
  metalness: value2.value * 1,
});
watch(
  [value1, value2],
  () => {
    console.log(value1.value, value2.value);
    material.roughness = value1.value * 1;
    material.metalness = value2.value * 1;
    render();
  },
  { deep: true }
);
function init() {
  const container = document.getElementById("container");
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.25, 20);
  camera.position.set(-1.8, 0.6, 2.7);
  scene = new THREE.Scene();
  loader.load("mesh/sm_car.gltf", async function (gltf) {
    console.log(gltf.scene);
    wheels = gltf.scene.getObjectByName("Wheel");
    const body = gltf.scene.getObjectByName("Object_37009");
    body.material = material;
    // item.material.aoMap = null;
    scene.add(gltf.scene);
    render();
  });
  new RGBELoader().load("textures/venice_sunset_1k.hdr", function (texture) {
    texture.mapping = THREE.EquirectangularReflectionMapping;
    texture.minFilter = THREE.LinearMipmapLinearFilter;
    texture.generateMipmaps = true;
    scene.background = texture;
    scene.environment = texture;
    render();
  });

  renderer = new THREE.WebGPURenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  container.appendChild(renderer.domElement);

  const controls = new OrbitControls(camera, renderer.domElement);
  controls.addEventListener("change", render); // use if there is no animation loop
  controls.minDistance = 2;
  controls.maxDistance = 10;
  controls.target.set(0, 0, -0.2);
  controls.update();
  window.addEventListener("resize", onWindowResize);
}

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  render();
}
function render() {
  renderer.renderAsync(scene, camera);
}
</script>
